package org.vaadinpa.gui;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.vaadinpa.gui.views.WelcomeView;

import com.vaadin.ui.Component;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Reindeer;

@SuppressWarnings("serial")
public class MainLayout extends GridLayout {

	private AbstractView currentView;
	private final Map<Class<? extends AbstractView>, AbstractView> createdViews = new HashMap<Class<? extends AbstractView>, AbstractView>();

	private final VerticalLayout mainViewholder = new VerticalLayout();
	private Header header;

	public MainLayout() {

		super(2, 3);
		setColumnExpandRatio(1, 1);
		setRowExpandRatio(1, 1);
		setSizeFull();
		addStyleName(Reindeer.LAYOUT_BLACK);

		header = new Header();
		addComponent(header, 0, 0, 1, 0);

		Menu menu = new Menu(this);
		addComponent(menu, 0, 1);

		currentView = new WelcomeView();

		mainViewholder.setSizeFull();
		mainViewholder.addComponent(currentView);
		mainViewholder.setExpandRatio(currentView, 1);

		addComponent(mainViewholder, 1, 1);

	}

	public void setCurrentView(Class<? extends AbstractView> clazz) {
		AbstractView next = null;
		if (createdViews.containsKey(clazz)) {
			next = createdViews.get(clazz);
		} else {
			try {
				next = clazz.newInstance();
				createdViews.put(next.getClass(), next);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		currentView = next;

		Iterator<Component> i = mainViewholder.getComponentIterator();
		boolean found = false;
		while (i.hasNext()) {
			AbstractView v = (AbstractView) i.next();
			if (v.equals(currentView)) {
				mainViewholder.setExpandRatio(v, 1);
				v.setVisible(true);
				found = true;
			} else {
				mainViewholder.setExpandRatio(v, 0);
				v.setVisible(false);
			}
		}
		if (!found) {
			mainViewholder.addComponent(currentView);
			mainViewholder.setExpandRatio(currentView, 1);
			currentView.setVisible(true);
		}
		currentView.reload();

		refresh();
	}

	public void refresh() {
		header.reload();
		if (currentView != null) {
			currentView.reload();
		}
	}
}
